<template>
	<AdminLayout activeKey="chat" :breadcrumbs="['首页','客服聊天']" tabTitle="客服聊天">
		<view class="chat-page">
			<!-- 聊天主容器 -->
			<view class="chat-container">
				<!-- 左侧用户列表 -->
				<view class="chat-sidebar">
					<!-- 搜索栏 -->
					<view class="search-bar">
						<view class="search-input-wrapper">
							<text class="iconfont icon-sousuo search-icon"></text>
							<input class="search-input" placeholder="搜索用户..." v-model="searchKeyword" @confirm="loadUserList" />
							<text v-if="searchKeyword" class="iconfont icon-guanbi clear-btn" @click="clearSearch"></text>
						</view>
					</view>
					
					<!-- 筛选标签 -->
					<view class="filter-tabs">
						<view 
							class="filter-tab" 
							:class="{ active: activeFilter === filter.key }"
							v-for="filter in filterTabs" 
							:key="filter.key"
							@click="switchFilter(filter.key)"
						>
							<text class="filter-text">{{ filter.label }}</text>
							<view v-if="filter.count > 0" class="filter-badge">{{ filter.count }}</view>
						</view>
					</view>
					
					<!-- 用户列表 -->
					<scroll-view class="user-list" scroll-y="true" :show-scrollbar="false">
						<view 
							class="user-item" 
							:class="{ active: selectedUser?.id === user.id, unread: user.unreadCount > 0 }"
							v-for="user in filteredUsers" 
							:key="user.id"
							@click="selectUser(user)"
						>
							<!-- 用户头像 -->
							<view class="user-avatar">
								<image v-if="user.avatar" :src="user.avatar" class="avatar-img" />
								<view v-else class="avatar-placeholder">
									<text class="avatar-text">{{ getAvatarText(user.nickname) }}</text>
								</view>
								<view v-if="user.isOnline" class="online-dot"></view>
							</view>
							
							<!-- 用户信息 -->
							<view class="user-info">
								<view class="user-header">
									<text class="user-nickname">{{ user.nickname }}</text>
									<text class="last-time">{{ formatTime(user.lastMessageTime) }}</text>
								</view>
								<view class="user-message">
									<text class="message-preview">{{ user.lastMessage || '暂无消息' }}</text>
									<view v-if="user.unreadCount > 0" class="unread-badge">{{ user.unreadCount }}</view>
								</view>
							</view>
						</view>
						
						<!-- 空状态 -->
						<view v-if="filteredUsers.length === 0" class="empty-state">
							<text class="iconfont icon-zanwushuju empty-icon"></text>
							<text class="empty-text">暂无用户消息</text>
						</view>
					</scroll-view>
				</view>
				
				<!-- 右侧聊天区域 -->
				<view class="chat-main">
					<!-- 聊天头部 -->
					<view v-if="selectedUser" class="chat-header">
						<view class="chat-user-info">
							<view class="chat-avatar">
								<image v-if="selectedUser.avatar" :src="selectedUser.avatar" class="avatar-img" />
								<view v-else class="avatar-placeholder">
									<text class="avatar-text">{{ getAvatarText(selectedUser.nickname) }}</text>
								</view>
								<view v-if="selectedUser.isOnline" class="online-dot"></view>
							</view>
							<view class="chat-user-details">
								<view class="user-name-row">
									<text class="chat-user-name">{{ selectedUser.nickname }}</text>
									<view class="user-status" :class="{ online: selectedUser.isOnline }">
										<text class="status-dot"></text>
										<text class="status-text">{{ selectedUser.isOnline ? '在线' : '离线' }}</text>
									</view>
								</view>
								<text class="chat-user-id">ID: {{ selectedUser.id }}</text>
							</view>
						</view>
						
					<!-- 聊天操作按钮 -->
					<view class="chat-actions">
						<button class="action-btn" @click="showUserProfile">
							<text class="iconfont icon-yonghu"></text>
							<text class="btn-text">资料</text>
						</button>
						<button class="action-btn" @click="showUserStatistics">
							<text class="iconfont icon-shuju"></text>
							<text class="btn-text">统计</text>
						</button>
						<button class="action-btn primary" @click="showHistoryPanel">
							<text class="iconfont icon-lishi"></text>
							<text class="btn-text">历史</text>
						</button>
						<button class="action-btn warning" @click="showQuickActions">
							<text class="iconfont icon-gongju"></text>
							<text class="btn-text">快捷</text>
						</button>
						<button class="action-btn danger" @click="endChat">
							<text class="iconfont icon-guanbi"></text>
							<text class="btn-text">结束</text>
						</button>
					</view>
					</view>
					
					<!-- 聊天消息区域 -->
					<view class="chat-content">
						<scroll-view 
							v-if="selectedUser" 
							class="message-list" 
							scroll-y="true" 
							:scroll-top="scrollTop"
							:show-scrollbar="false"
							@scrolltoupper="loadMoreHistoryMessages"
						>
							<!-- 搜索结果提示条 -->
							<view v-if="!userListTimer" class="search-result-tip">
								<view class="tip-content">
									<text class="iconfont icon-sousuo tip-icon"></text>
									<text class="tip-text">正在查看搜索结果（实时更新已暂停）</text>
									<button class="tip-btn" @click="clearFilters">
										<text class="iconfont icon-shuaxin"></text>
										<text>恢复实时</text>
									</button>
								</view>
							</view>
							
							<!-- 加载更多历史消息提示 -->
							<view v-if="hasMoreHistory && messages.length > 0 && userListTimer" class="load-more" @click="loadMoreHistoryMessages">
								<text v-if="isLoadingMore" class="iconfont icon-loading rotating load-icon"></text>
								<text v-else class="iconfont icon-shuaxin load-icon"></text>
								<text class="load-text">{{ isLoadingMore ? '加载中...' : '向上滚动或点击加载更早的消息' }}</text>
							</view>
							
						<!-- 消息列表 -->
						<block v-for="(item, index) in messagesWithTimeline" :key="index">
							<!-- 时间分隔线 -->
							<view v-if="item.type === 'timeline'" class="time-divider">
								<view class="time-divider-line"></view>
								<view class="time-divider-text">{{ item.text }}</view>
								<view class="time-divider-line"></view>
							</view>
							
							<!-- 消息项 -->
							<view 
								v-else
								class="message-item" 
								:class="{ 'message-right': item.isAdmin, 'message-left': !item.isAdmin }"
							>
								<view class="message-avatar">
									<image v-if="item.avatar" :src="item.avatar" class="avatar-img" />
									<view v-else class="avatar-placeholder">
										<text class="avatar-text">{{ getAvatarText(item.senderName) }}</text>
									</view>
								</view>
								
								<view class="message-content">
									<view class="message-header">
										<text class="sender-name">{{ item.senderName }}</text>
										<text class="message-time">{{ formatMessageTime(item.createTime) }}</text>
									</view>
									
									<!-- 文本消息 -->
									<view v-if="item.type === 'text'" class="message-bubble text-message">
										<text class="message-text">{{ item.content }}</text>
									</view>
									
									<!-- 图片消息 -->
									<view v-else-if="item.type === 'image'" class="message-bubble image-message" @click="previewImage(getImageUrl(item))">
										<view v-if="getImageUrl(item)" class="image-container">
											<image 
												:src="getImageUrl(item)" 
												class="message-image" 
												mode="aspectFit"
												@error="onImageError"
												@load="onImageLoad"
												:data-url="getImageUrl(item)"
											/>
										</view>
										<view v-else class="image-error">
											<text class="iconfont icon-tupian error-icon"></text>
											<text class="error-text">图片加载失败</text>
											<text class="retry-text" @click.stop="retryLoadMessage(item)">点击重试</text>
										</view>
									</view>
									
									<!-- 系统消息 -->
									<view v-else-if="item.type === 'system'" class="system-message">
										<text class="system-text">{{ item.content }}</text>
									</view>
									
									<!-- 消息状态 -->
									<view v-if="item.isAdmin && item.status" class="message-status">
										<text v-if="item.status === 'sending'" class="status-text sending">发送中</text>
										<text v-else-if="item.status === 'sent'" class="status-text sent">已发送</text>
										<text v-else-if="item.status === 'read'" class="status-text read">已读</text>
										<text v-else-if="item.status === 'failed'" class="status-text failed" @click="resendMessage(item)">发送失败，点击重试</text>
									</view>
								</view>
							</view>
						</block>
							
							<!-- 空状态 -->
							<view v-if="messages.length === 0" class="empty-messages">
								<text class="iconfont icon-liaotian empty-chat-icon"></text>
								<text class="empty-chat-text">开始与用户聊天吧</text>
							</view>
						</scroll-view>
						
						<!-- 未选择用户状态 -->
						<view v-else class="no-chat-selected">
							<text class="iconfont icon-liaotian no-chat-icon"></text>
							<text class="no-chat-title">客服聊天</text>
							<text class="no-chat-desc">选择左侧用户开始聊天</text>
						</view>
					</view>
					
					<!-- 消息输入区域 -->
					<view v-if="selectedUser" class="chat-input-area">
						<!-- 快捷回复 -->
						<view v-if="showQuickReplies" class="quick-replies">
							<scroll-view class="quick-reply-list" scroll-x="true" :show-scrollbar="false">
								<view 
									class="quick-reply-item" 
									v-for="reply in quickReplies" 
									:key="reply.id"
									@click="insertQuickReply(reply.content)"
								>
									<text class="quick-reply-text">{{ reply.content }}</text>
								</view>
							</scroll-view>
						</view>
						
						<!-- 输入工具栏 -->
						<view class="input-toolbar">
							<button class="toolbar-btn quick-btn" @click="toggleQuickReplies" :class="{ active: showQuickReplies }">
								<text class="iconfont icon-kuaijiehuifu toolbar-icon"></text>
								<text class="toolbar-text">快捷回复</text>
							</button>
							<button class="toolbar-btn image-btn" @click="chooseImage">
								<text class="iconfont icon-tupian toolbar-icon"></text>
								<text class="toolbar-text">发送图片</text>
							</button>
						</view>
						
						<!-- 消息输入框 -->
						<view class="message-input-container">
							<textarea 
								class="message-input" 
								placeholder="输入消息..." 
								v-model="inputMessage"
								:auto-height="true"
								:max-height="120"
								@confirm="sendMessage"
								@input="onInputChange"
							></textarea>
							<button 
								class="send-btn" 
								:class="{ active: inputMessage.trim(), loading: isSending }"
								@click="sendMessage"
								:disabled="!inputMessage.trim() || isSending"
							>
								<view class="send-btn-content">
									<text v-if="isSending" class="send-text">发送中</text>
									<text v-else class="send-text">发送</text>
									<view class="send-icon-wrapper">
										<text v-if="isSending" class="iconfont icon-loading send-icon rotating"></text>
										<text v-else class="iconfont icon-fasong send-icon"></text>
									</view>
								</view>
							</button>
						</view>
						
						<!-- 输入提示 -->
						<view class="input-tips">
							<text class="tip-text">按 Enter 发送消息，Shift + Enter 换行</text>
							<text class="typing-indicator" v-if="isUserTyping">{{ selectedUser.nickname }} 正在输入...</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 用户资料抽屉 -->
			<view class="drawer-mask" v-if="showProfileDrawer" @click="closeProfileDrawer"></view>
			<view class="drawer-container" :class="{ 'drawer-show': showProfileDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">用户资料</text>
					<text class="iconfont icon-guanbi drawer-close" @click="closeProfileDrawer"></text>
				</view>
				
				<scroll-view class="drawer-content" scroll-y="true">
					<view v-if="userProfile" class="profile-section">
						<!-- 用户头像和基本信息 -->
						<view class="profile-avatar-section">
							<view class="profile-avatar-wrapper">
								<image v-if="userProfile.avatar" :src="userProfile.avatar" class="profile-avatar-img" />
								<view v-else class="profile-avatar-placeholder">
									<text class="profile-avatar-text">{{ getAvatarText(userProfile.nickname) }}</text>
								</view>
								<view v-if="userProfile.isOnline" class="profile-online-badge">在线</view>
							</view>
						</view>
						
						<!-- 详细信息列表 -->
						<view class="profile-info-list">
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-yonghu info-icon"></text>
									<text class="info-label-text">昵称</text>
								</view>
								<text class="info-value">{{ userProfile.nickname }}</text>
							</view>
							
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-bianhao info-icon"></text>
									<text class="info-label-text">用户ID</text>
								</view>
								<text class="info-value">{{ userProfile.id }}</text>
							</view>
							
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-shouji info-icon"></text>
									<text class="info-label-text">手机号</text>
								</view>
								<text class="info-value">{{ userProfile.mobile || '未绑定' }}</text>
							</view>
							
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-shijian info-icon"></text>
									<text class="info-label-text">注册时间</text>
								</view>
								<text class="info-value">{{ formatDateTime(userProfile.register_date) }}</text>
							</view>
							
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-denglu info-icon"></text>
									<text class="info-label-text">最后登录</text>
								</view>
								<text class="info-value">{{ formatDateTime(userProfile.last_login_date) }}</text>
							</view>
							
							<view class="profile-info-item">
								<view class="info-label">
									<text class="iconfont icon-zhuangtai info-icon"></text>
									<text class="info-label-text">账号状态</text>
								</view>
								<text class="info-value" :class="{ 'status-active': userProfile.status === 0, 'status-banned': userProfile.status !== 0 }">
									{{ userProfile.status === 0 ? '正常' : '已禁用' }}
								</text>
							</view>
						</view>
					</view>
					
					<view v-else class="drawer-loading">
						<text class="iconfont icon-loading rotating"></text>
						<text class="loading-text">加载中...</text>
					</view>
				</scroll-view>
			</view>
			
			<!-- 用户统计抽屉 -->
			<view class="drawer-mask" v-if="showStatisticsDrawer" @click="closeStatisticsDrawer"></view>
			<view class="drawer-container" :class="{ 'drawer-show': showStatisticsDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">用户统计</text>
					<text class="iconfont icon-guanbi drawer-close" @click="closeStatisticsDrawer"></text>
				</view>
				
				<scroll-view class="drawer-content" scroll-y="true">
					<view v-if="userStatistics" class="statistics-section">
						<!-- 统计卡片 -->
						<view class="statistics-cards">
							<view class="stat-card stat-card-blue">
								<view class="stat-icon-wrapper">
									<text class="iconfont icon-renwu stat-card-icon"></text>
								</view>
								<view class="stat-info">
									<text class="stat-value">{{ userStatistics.publishedTasks || 0 }}</text>
									<text class="stat-label">发布任务数</text>
								</view>
							</view>
							
							<view class="stat-card stat-card-green">
								<view class="stat-icon-wrapper">
									<text class="iconfont icon-wancheng stat-card-icon"></text>
								</view>
								<view class="stat-info">
									<text class="stat-value">{{ userStatistics.completedTasks || 0 }}</text>
									<text class="stat-label">完成任务数</text>
								</view>
							</view>
							
							<view class="stat-card stat-card-orange">
								<view class="stat-icon-wrapper">
									<text class="iconfont icon-jifen stat-card-icon"></text>
								</view>
								<view class="stat-info">
									<text class="stat-value">{{ userStatistics.points || 0 }}</text>
									<text class="stat-label">当前积分</text>
								</view>
							</view>
							
							<view class="stat-card stat-card-purple">
								<view class="stat-icon-wrapper">
									<text class="iconfont icon-xinyong stat-card-icon"></text>
								</view>
								<view class="stat-info">
									<text class="stat-value">{{ userStatistics.creditLevel || 'A' }}</text>
									<text class="stat-label">信用等级</text>
								</view>
							</view>
					</view>
				</view>
					
					<view v-else class="drawer-loading">
						<text class="iconfont icon-loading rotating"></text>
						<text class="loading-text">加载中...</text>
					</view>
				</scroll-view>
			</view>
			
			<!-- 历史记录高级查看抽屉 -->
			<view class="drawer-mask" v-if="showHistoryDrawer" @click="closeHistoryDrawer"></view>
			<view class="drawer-container history-drawer" :class="{ 'drawer-show': showHistoryDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">历史记录</text>
					<text class="iconfont icon-guanbi drawer-close" @click="closeHistoryDrawer"></text>
				</view>
				
				<scroll-view class="drawer-content" scroll-y="true">
					<!-- 会话统计信息 -->
					<view v-if="messageStatistics" class="history-statistics">
						<view class="stat-title">会话统计</view>
						<view class="stat-grid">
							<view class="stat-item">
								<text class="stat-num">{{ messageStatistics.totalMessages }}</text>
								<text class="stat-label">总消息数</text>
							</view>
							<view class="stat-item">
								<text class="stat-num">{{ messageStatistics.conversationDays }}</text>
								<text class="stat-label">会话天数</text>
							</view>
							<view class="stat-item">
								<text class="stat-num">{{ messageStatistics.userMessages }}</text>
								<text class="stat-label">用户消息</text>
							</view>
							<view class="stat-item">
								<text class="stat-num">{{ messageStatistics.adminMessages }}</text>
								<text class="stat-label">客服消息</text>
							</view>
						</view>
						<view class="stat-time-info">
							<view class="time-info-item">
								<text class="time-label">首次咨询：</text>
								<text class="time-value">{{ formatDateTime(messageStatistics.firstMessageTime) }}</text>
							</view>
							<view class="time-info-item">
								<text class="time-label">最后消息：</text>
								<text class="time-value">{{ formatDateTime(messageStatistics.lastMessageTime) }}</text>
							</view>
						</view>
					</view>
					
					<!-- 搜索和筛选区域 -->
					<view class="history-search-section">
						<view class="search-title">搜索与筛选</view>
						
						<!-- 关键词搜索 -->
						<view class="search-field">
							<text class="field-label">关键词搜索</text>
							<view class="search-input-wrapper-new">
								<input 
									class="search-input-new" 
									type="text"
									placeholder="搜索消息内容..." 
									v-model="historySearchKeyword"
									@input="onSearchInput"
									@confirm="searchHistoryMessages"
								/>
								<button class="search-btn-new" @click="searchHistoryMessages">
									<text class="iconfont icon-sousuo"></text>
								</button>
							</view>
						</view>
						
						<!-- 日期范围筛选 -->
						<view class="date-filter-section">
							<view class="date-field">
								<text class="field-label">开始日期</text>
								<picker mode="date" :value="historyStartDate" @change="onStartDateChange">
									<view class="date-picker">
										<text class="date-text">{{ historyStartDate || '选择开始日期' }}</text>
										<text class="iconfont icon-riqi"></text>
									</view>
								</picker>
							</view>
							
							<view class="date-field">
								<text class="field-label">结束日期</text>
								<picker mode="date" :value="historyEndDate" @change="onEndDateChange">
									<view class="date-picker">
										<text class="date-text">{{ historyEndDate || '选择结束日期' }}</text>
										<text class="iconfont icon-riqi"></text>
									</view>
								</picker>
							</view>
						</view>
						
						<!-- 消息类型筛选 -->
						<view class="type-filter-section">
							<text class="field-label">消息类型</text>
							<view class="type-buttons">
								<button 
									class="type-btn" 
									:class="{ active: historyMessageType === '' }"
									@click="historyMessageType = ''; searchHistoryMessages()"
								>
									全部
								</button>
								<button 
									class="type-btn" 
									:class="{ active: historyMessageType === 'text' }"
									@click="historyMessageType = 'text'; searchHistoryMessages()"
								>
									文本
								</button>
								<button 
									class="type-btn" 
									:class="{ active: historyMessageType === 'image' }"
									@click="historyMessageType = 'image'; searchHistoryMessages()"
								>
									图片
								</button>
							</view>
						</view>
						
						<!-- 快捷日期筛选 -->
						<view class="quick-date-section">
							<text class="field-label">快捷筛选</text>
							<view class="quick-date-buttons">
								<button class="quick-date-btn" @click="setQuickDateRange('today')">今天</button>
								<button class="quick-date-btn" @click="setQuickDateRange('yesterday')">昨天</button>
								<button class="quick-date-btn" @click="setQuickDateRange('week')">最近7天</button>
								<button class="quick-date-btn" @click="setQuickDateRange('month')">最近30天</button>
								<button class="quick-date-btn" @click="clearFilters">清除筛选</button>
							</view>
						</view>
					</view>
					
					<!-- 导出按钮区域 -->
					<view class="export-section">
						<button class="export-btn" @click="exportChatHistory('text')">
							<text class="iconfont icon-daochu"></text>
							<text class="btn-text">导出为文本</text>
						</button>
						<button class="export-btn" @click="exportChatHistory('json')">
							<text class="iconfont icon-daochu"></text>
							<text class="btn-text">导出为JSON</text>
						</button>
					</view>
				</scroll-view>
			</view>
			
			<!-- 快捷操作抽屉 -->
			<view class="drawer-mask" v-if="showQuickActionsDrawer" @click="closeQuickActionsDrawer"></view>
			<view class="drawer-container" :class="{ 'drawer-show': showQuickActionsDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">快捷操作</text>
					<text class="iconfont icon-guanbi drawer-close" @click="closeQuickActionsDrawer"></text>
				</view>
				
				<scroll-view class="drawer-content" scroll-y="true">
					<view v-if="selectedUser" class="quick-actions-section">
						<!-- 积分调整 -->
						<view class="action-card">
							<view class="action-card-header">
								<text class="iconfont icon-jifen action-icon"></text>
								<text class="action-title">积分调整</text>
							</view>
							<view class="action-card-body">
								<view class="current-value">
									<text class="value-label">当前积分：</text>
									<text class="value-number">{{ userStatistics?.points || 0 }}</text>
								</view>
								<view class="input-group">
									<input 
										class="action-input drawer-input" 
										type="number" 
										v-model.number="pointsAdjust"
										placeholder="输入调整积分（可为负数）"
									/>
								</view>
								<view class="quick-buttons">
									<button class="quick-action-btn" @click="pointsAdjust = 10">+10</button>
									<button class="quick-action-btn" @click="pointsAdjust = 50">+50</button>
									<button class="quick-action-btn" @click="pointsAdjust = 100">+100</button>
									<button class="quick-action-btn danger" @click="pointsAdjust = -10">-10</button>
									<button class="quick-action-btn danger" @click="pointsAdjust = -50">-50</button>
								</view>
								<button class="action-submit-btn" @click="submitPointsAdjust">
									<text class="iconfont icon-queding"></text>
									<text>确认调整积分</text>
								</button>
							</view>
						</view>
						
						<!-- 信用分调整 -->
						<view class="action-card">
							<view class="action-card-header">
								<text class="iconfont icon-xinyong action-icon"></text>
								<text class="action-title">信用分调整</text>
							</view>
							<view class="action-card-body">
								<view class="current-value">
									<text class="value-label">当前信用分：</text>
									<text class="value-number">{{ userStatistics?.creditScore || 0 }}</text>
								</view>
								<view class="input-group">
									<input 
										class="action-input drawer-input" 
										type="number" 
										v-model.number="creditScoreAdjust"
										placeholder="输入调整信用分（可为负数）"
									/>
								</view>
								<view class="quick-buttons">
									<button class="quick-action-btn" @click="creditScoreAdjust = 10">+10</button>
									<button class="quick-action-btn" @click="creditScoreAdjust = 50">+50</button>
									<button class="quick-action-btn" @click="creditScoreAdjust = 100">+100</button>
									<button class="quick-action-btn danger" @click="creditScoreAdjust = -10">-10</button>
									<button class="quick-action-btn danger" @click="creditScoreAdjust = -50">-50</button>
								</view>
								<button class="action-submit-btn" @click="submitCreditScore">
									<text class="iconfont icon-queding"></text>
									<text>确认调整信用分</text>
								</button>
							</view>
						</view>
						
						<!-- 违规标记 -->
						<view class="action-card">
							<view class="action-card-header">
								<text class="iconfont icon-jinggao action-icon"></text>
								<text class="action-title">违规标记</text>
							</view>
							<view class="action-card-body">
								<view class="violation-types">
									<button 
										class="violation-btn" 
										:class="{ active: violationType === 'spam' }"
										@click="violationType = 'spam'"
									>
										<text class="iconfont icon-laji"></text>
										<text>垃圾信息</text>
									</button>
									<button 
										class="violation-btn" 
										:class="{ active: violationType === 'fraud' }"
										@click="violationType = 'fraud'"
									>
										<text class="iconfont icon-qipian"></text>
										<text>欺诈行为</text>
									</button>
									<button 
										class="violation-btn" 
										:class="{ active: violationType === 'abuse' }"
										@click="violationType = 'abuse'"
									>
										<text class="iconfont icon-wurao"></text>
										<text>恶意骚扰</text>
									</button>
									<button 
										class="violation-btn" 
										:class="{ active: violationType === 'other' }"
										@click="violationType = 'other'"
									>
										<text class="iconfont icon-qita"></text>
										<text>其他违规</text>
									</button>
								</view>
								<textarea 
									class="violation-reason drawer-input" 
									placeholder="请输入违规原因（必填）..."
									v-model="violationReason"
									maxlength="200"
								></textarea>
								<view class="action-buttons-row">
									<button class="action-submit-btn warning" @click="submitViolation('warning')">
										<text class="iconfont icon-jinggao"></text>
										<text>警告</text>
									</button>
									<button class="action-submit-btn danger" @click="submitViolation('ban')">
										<text class="iconfont icon-jinzhi"></text>
										<text>禁用账号</text>
									</button>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</AdminLayout>
</template>

<script>
import AdminLayout from '@/components/AdminLayout.vue'

export default {
	components: { 
		AdminLayout
	},
	data() {
		return {
			// 搜索和筛选
			searchKeyword: '',
			activeFilter: 'all',
			filterTabs: [
				{ key: 'all', label: '全部', count: 0 },
				{ key: 'unread', label: '未读', count: 0 }
			],
			
			// 用户数据
			users: [],
			selectedUser: null,
			
			// 消息数据
			messages: [],
			scrollTop: 0,
			hasMoreMessages: false,
			
			// 输入相关
			inputMessage: '',
			isSending: false,
			isUserTyping: false,
			
			// 快捷回复
			showQuickReplies: false,
			quickReplies: [
				{ id: 1, content: '您好，有什么可以帮助您的吗？' },
				{ id: 2, content: '请稍等，我为您查询一下' },
				{ id: 3, content: '感谢您的反馈，我们会及时处理' },
				{ id: 4, content: '问题已为您解决，还有其他需要帮助的吗？' },
				{ id: 5, content: '感谢您的咨询，祝您生活愉快！' }
			],
			
		// 实时更新定时器
		userListTimer: null,
		messageTimer: null,
		
		// 抽屉相关
		showProfileDrawer: false,
		showStatisticsDrawer: false,
		userProfile: null,
		userStatistics: null,
		
		// 历史记录相关
		showHistoryDrawer: false,
		currentPage: 1,
		isLoadingMore: false,
		hasMoreHistory: true,
		historySearchKeyword: '',
		historyStartDate: '',
		historyEndDate: '',
		historyMessageType: '',
		messageStatistics: null,
		isLoadingStatistics: false,
		
		// 快捷操作相关
		showQuickActionsDrawer: false,
		pointsAdjust: 0,
		creditScoreAdjust: 0,
		violationType: '',
		violationReason: ''
	}
},
	
	computed: {
		// 筛选后的用户列表
		filteredUsers() {
			let filtered = this.users
			
			// 搜索筛选
			if (this.searchKeyword) {
				filtered = filtered.filter(user => 
					user.nickname.toLowerCase().includes(this.searchKeyword.toLowerCase())
				)
			}
			
			// 状态筛选
			switch (this.activeFilter) {
				case 'unread':
					filtered = filtered.filter(user => user.unreadCount > 0)
					break
			}
			
			// 按最后消息时间排序
			return filtered.sort((a, b) => b.lastMessageTime - a.lastMessageTime)
		},
		
		// 带时间分隔线的消息列表
		messagesWithTimeline() {
			if (this.messages.length === 0) return []
			
			const result = []
			let lastTimestamp = null
			const TIME_GAP = 5 * 60 * 1000 // 5分钟
			
			this.messages.forEach((message, index) => {
				const currentTimestamp = message.createTime
				
				// 第一条消息或时间间隔超过5分钟时，插入时间分隔线
				if (lastTimestamp === null || (currentTimestamp - lastTimestamp) > TIME_GAP) {
					const timeText = this.getTimelineText(currentTimestamp)
					result.push({
						type: 'timeline',
						text: timeText,
						id: 'timeline_' + index
					})
				}
				
				// 添加消息
				result.push(message)
				lastTimestamp = currentTimestamp
			})
			
			return result
		}
	},
	
	onReady() {
		this.loadUserList()
		this.startRealtimeUpdates()
	},
	
	onUnload() {
		this.stopRealtimeUpdates()
	},
	
	onHide() {
		this.stopRealtimeUpdates()
	},
	
	onShow() {
		if (this.selectedUser) {
			this.startRealtimeUpdates()
		}
	},
	
	methods: {
		// 加载用户列表
		async loadUserList() {
			console.log('开始加载用户列表...')
			try {
				const res = await uniCloud.callFunction({
					name: 'adminChat',
					data: {
						action: 'getUserList',
						page: 1,
						pageSize: 50,
						keyword: this.searchKeyword
					}
				})
				
				console.log('云函数调用结果:', res)
				
				if (res.result && res.result.code === 200) {
					this.users = res.result.data || []
					this.updateFilterCounts()
					console.log('用户列表加载成功，用户数量:', this.users.length)
				} else {
					const errorMsg = res.result ? res.result.msg : '未知错误'
					console.error('获取用户列表失败:', errorMsg, res.result)
					uni.showToast({
						title: '获取用户列表失败: ' + errorMsg,
						icon: 'none',
						duration: 3000
					})
				}
			} catch (error) {
				console.error('加载用户列表错误:', error)
				uni.showToast({
					title: '网络错误，请检查云函数部署',
					icon: 'none',
					duration: 3000
				})
			}
		},
		
		// 启动实时更新
		startRealtimeUpdates() {
			// 定时刷新用户列表（每5秒）
			this.userListTimer = setInterval(() => {
				this.loadUserList()
			}, 5000)
			
			// 如果有选中用户，定时刷新聊天消息（每3秒）
			this.messageTimer = setInterval(() => {
				if (this.selectedUser && this.selectedUser.id) {
					this.loadChatMessages(this.selectedUser.id, false) // 静默刷新
				}
			}, 3000)
		},
		
		// 停止实时更新
		stopRealtimeUpdates() {
			if (this.userListTimer) {
				clearInterval(this.userListTimer)
				this.userListTimer = null
			}
			if (this.messageTimer) {
				clearInterval(this.messageTimer)
				this.messageTimer = null
			}
		},
		
		// 更新筛选标签计数
		updateFilterCounts() {
			this.filterTabs[0].count = this.users.length
			this.filterTabs[1].count = this.users.filter(user => user.unreadCount > 0).length
		},
		
		// 清除搜索
		clearSearch() {
			this.searchKeyword = ''
			this.loadUserList()
		},
		
		// 切换筛选
		switchFilter(filterKey) {
			this.activeFilter = filterKey
		},
		
	// 选择用户
	async selectUser(user) {
		console.log('[selectUser] 选择用户:', user.nickname)
		this.selectedUser = user
		// 标记消息为已读
		user.unreadCount = 0
		this.updateFilterCounts()
		// 重置分页状态
		this.currentPage = 1
		this.hasMoreHistory = true
		this.messages = []
		// 加载聊天记录（云函数会自动标记消息为已读）
		await this.loadChatMessages(user.id)
		// 确保滚动到底部
		this.$nextTick(() => {
			setTimeout(() => {
				this.scrollToBottom()
				console.log('[selectUser] 用户选择完成，已滚动到底部')
			}, 200)
		})
		// 重新加载用户列表以更新未读数
		setTimeout(() => {
			this.loadUserList()
		}, 500)
	},
		
	// 加载聊天消息
	async loadChatMessages(userId, showLoading = true) {
		if (!userId) return
		
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'getMessages',
					userId: userId,
					page: 1,
					pageSize: 50
				}
			})
			
			console.log('[loadChatMessages] 云函数返回结果:', res.result)
			
			if (res.result.code === 200) {
				const newMessages = res.result.data || []
				
				console.log('[loadChatMessages] 获取到消息数量:', newMessages.length)
				console.log('[loadChatMessages] 前5条消息:', newMessages.slice(0, 5))
				
				// 检查是否有新消息
				if (this.messages.length > 0 && newMessages.length > this.messages.length) {
					// 有新消息，播放提示音（可选）
					this.playNotificationSound()
				}
				
				this.messages = newMessages
				
				// 更新用户列表中的未读数（云函数已经标记为已读）
				const user = this.users.find(u => u.id === userId)
				if (user) {
					user.unreadCount = 0
					this.updateFilterCounts()
				}
				
				// 预加载云存储图片的临时链接
				await this.preloadCloudImages()
				
				// 滚动到底部（延迟确保渲染完成）
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollToBottom()
					}, 100)
				})
			} else {
				if (showLoading) {
					console.error('[loadChatMessages] 获取聊天消息失败:', res.result.msg)
					uni.showToast({
						title: '获取消息失败: ' + res.result.msg,
						icon: 'none',
						duration: 2000
					})
				}
			}
		} catch (error) {
			if (showLoading) {
				console.error('[loadChatMessages] 加载聊天消息错误:', error)
				uni.showToast({
					title: '加载消息失败',
					icon: 'none',
					duration: 2000
				})
			}
		}
	},
		
		// 播放通知音效
		playNotificationSound() {
			try {
				// 简单的提示音，可以替换为真实的音频文件
				uni.showToast({
					title: '收到新消息',
					icon: 'none',
					duration: 1000
				})
			} catch (error) {
				console.log('播放提示音失败:', error)
			}
		},
		
		// 滚动到底部
		scrollToBottom() {
			// 使用一个足够大的值确保滚动到底部
			// 每次调用时增加值以触发滚动更新
			this.scrollTop = this.scrollTop === 999999 ? 1000000 : 999999
			console.log('[scrollToBottom] 滚动到底部, scrollTop:', this.scrollTop)
		},
		
		// 加载更多消息
		loadMoreMessages() {
			// 模拟加载更多
			console.log('加载更多消息')
		},
		
		// 发送消息
		async sendMessage() {
			if (!this.inputMessage.trim() || this.isSending || !this.selectedUser) return
			
			this.isSending = true
			const content = this.inputMessage.trim()
			this.inputMessage = ''
			
			// 添加发送中的消息到界面
			const tempMessage = {
				id: 'temp_' + Date.now(),
				type: 'text',
				content: content,
				senderName: '客服小助手',
				isAdmin: true,
				createTime: new Date().getTime(),
				status: 'sending'
			}
			this.messages.push(tempMessage)
			
			// 滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom()
			})
			
			try {
				const res = await uniCloud.callFunction({
					name: 'adminChat',
					data: {
						action: 'sendMessage',
						userId: this.selectedUser.id,
						content: content,
						type: 'text'
					}
				})
				
			if (res.result.code === 200) {
				// 替换临时消息
				const index = this.messages.findIndex(m => m.id === tempMessage.id)
				if (index !== -1) {
					this.messages.splice(index, 1, res.result.data)
				}
				
				// 更新用户最后消息
				this.selectedUser.lastMessage = content
				this.selectedUser.lastMessageTime = new Date().getTime()
				
				// 滚动到底部
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollToBottom()
					}, 100)
				})
				
				// 立即刷新用户列表
				setTimeout(() => {
					this.loadUserList()
				}, 500)
			} else {
				// 发送失败，更新状态
				tempMessage.status = 'failed'
				console.error('发送消息失败:', res.result.msg)
			}
			} catch (error) {
				tempMessage.status = 'failed'
				console.error('发送消息错误:', error)
			} finally {
				this.isSending = false
			}
		},
		
		// 重发消息
		async resendMessage(message) {
			if (!this.selectedUser) return
			
			message.status = 'sending'
			
			try {
				// 如果是图片消息且内容是本地路径，需要重新上传
				if (message.type === 'image' && message.content.startsWith('file://')) {
					// 重新上传图片
					const uploadRes = await uniCloud.uploadFile({
						filePath: message.content,
						cloudPath: 'chat-images/' + Date.now() + '_' + Math.random().toString(36).substr(2, 9) + '.jpg'
					})
					
					if (uploadRes.fileID) {
						// 更新消息的imageUrl为云存储的fileID
						message.imageUrl = uploadRes.fileID
						message.content = '[图片]'
					} else {
						throw new Error('图片上传失败')
					}
				}
				
				const res = await uniCloud.callFunction({
					name: 'adminChat',
					data: {
						action: 'sendMessage',
						userId: this.selectedUser.id,
						content: message.content,
						type: message.type,
						imageUrl: message.imageUrl  // 传递imageUrl字段
					}
				})
				
				if (res.result && res.result.code === 200) {
					message.status = 'sent'
					message.id = res.result.data.id
					
					uni.showToast({
						title: '重发成功',
						icon: 'success'
					})
				} else {
					message.status = 'failed'
					throw new Error(res.result ? res.result.msg : '重发失败')
				}
			} catch (error) {
				message.status = 'failed'
				console.error('重发消息失败:', error)
				uni.showToast({
					title: '重发失败: ' + (error.message || '未知错误'),
					icon: 'none'
				})
			}
		},
		
		// 输入变化
		onInputChange() {
			// 可以在这里处理输入状态
		},
		
		// 切换快捷回复
		toggleQuickReplies() {
			this.showQuickReplies = !this.showQuickReplies
		},
		
		// 插入快捷回复
		insertQuickReply(content) {
			this.inputMessage = content
			this.showQuickReplies = false
		},
		
		// 选择图片
		chooseImage() {
			if (!this.selectedUser) {
				uni.showToast({
					title: '请先选择用户',
					icon: 'none'
				})
				return
			}
			
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: async (res) => {
					const tempFilePath = res.tempFilePaths[0]
					
					// 显示上传中
					uni.showLoading({
						title: '上传中...'
					})
					
					// 添加发送中的消息到界面
					const tempMessage = {
						id: 'temp_image_' + Date.now(),
						type: 'image',
						content: tempFilePath, // 临时显示本地路径
						senderName: '客服小助手',
						isAdmin: true,
						createTime: new Date().getTime(),
						status: 'sending'
					}
					this.messages.push(tempMessage)
					
					// 滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom()
					})

					try {
						// 检查文件大小（限制为5MB）
						try {
							const fileInfo = uni.getFileInfoSync(tempFilePath)
							if (fileInfo.size > 5 * 1024 * 1024) {
								throw new Error('图片大小不能超过5MB')
							}
						} catch (sizeError) {
							console.warn('获取文件信息失败:', sizeError)
						}

						// 获取文件扩展名
						const fileName = tempFilePath.split('/').pop() || tempFilePath.split('\\').pop()
						const fileExtension = fileName.split('.').pop() || 'jpg'
						
						// 直接使用 uniCloud 上传文件
						const uploadRes = await uniCloud.uploadFile({
							filePath: tempFilePath,
							cloudPath: 'chat-images/' + Date.now() + '_' + Math.random().toString(36).substr(2, 9) + '.' + fileExtension
						})
						
						console.log('图片上传结果:', uploadRes)
						
						if (uploadRes.fileID) {
							// 发送图片消息，将fileID存储到imageUrl字段
							const res = await uniCloud.callFunction({
								name: 'adminChat',
								data: {
									action: 'sendMessage',
									userId: this.selectedUser.id,
									content: '[图片]',
									type: 'image',
									imageUrl: uploadRes.fileID  // 将fileID存储到imageUrl字段
								}
							})
							
					if (res.result && res.result.code === 200) {
						// 替换临时消息
						const index = this.messages.findIndex(m => m.id === tempMessage.id)
						if (index !== -1) {
							this.messages.splice(index, 1, res.result.data)
						}
						
						// 更新用户最后消息
						this.selectedUser.lastMessage = '[图片]'
						this.selectedUser.lastMessageTime = new Date().getTime()
						
						// 滚动到底部
						this.$nextTick(() => {
							setTimeout(() => {
								this.scrollToBottom()
							}, 100)
						})
						
						// 立即刷新用户列表
						setTimeout(() => {
							this.loadUserList()
						}, 500)
						
						uni.showToast({
							title: '发送成功',
							icon: 'success'
						})
					} else {
						throw new Error(res.result ? res.result.msg : '发送消息失败')
					}
						} else {
							throw new Error('文件上传失败')
						}
					} catch (error) {
						console.error('发送图片失败:', error)
						
						// 更新临时消息状态为失败
						tempMessage.status = 'failed'
						
						let errorMsg = '发送失败'
						if (error.message) {
							errorMsg = error.message
						} else if (typeof error === 'string') {
							errorMsg = error
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						})
					} finally {
						uni.hideLoading()
					}
				},
				fail: (error) => {
					console.error('选择图片失败:', error)
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		},
		
		
		// 预览图片
		previewImage(url) {
			uni.previewImage({
				urls: [url]
			})
		},
		
	// 显示用户资料
	async showUserProfile() {
		if (!this.selectedUser) return
		
		this.showProfileDrawer = true
		this.userProfile = null
		
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'getUserProfile',
					userId: this.selectedUser.id
				}
			})
			
			if (res.result && res.result.code === 200) {
				this.userProfile = res.result.data
			} else {
				uni.showToast({
					title: '获取用户资料失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('获取用户资料失败:', error)
			uni.showToast({
				title: '获取用户资料失败',
				icon: 'none'
			})
		}
	},
	
	// 关闭用户资料抽屉
	closeProfileDrawer() {
		this.showProfileDrawer = false
	},
	
	// 显示用户统计
	async showUserStatistics() {
		if (!this.selectedUser) return
		
		this.showStatisticsDrawer = true
		this.userStatistics = null
		
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'getUserStatistics',
					userId: this.selectedUser.id
				}
			})
			
			if (res.result && res.result.code === 200) {
				this.userStatistics = res.result.data
			} else {
				uni.showToast({
					title: '获取用户统计失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('获取用户统计失败:', error)
			uni.showToast({
				title: '获取用户统计失败',
				icon: 'none'
			})
		}
	},
	
	// 关闭用户统计抽屉
	closeStatisticsDrawer() {
		this.showStatisticsDrawer = false
	},
		
		// 结束聊天
		endChat() {
			uni.showModal({
				title: '结束聊天',
				content: '确定要结束与此用户的聊天吗？',
				success: (res) => {
					if (res.confirm) {
						this.selectedUser = null
						this.messages = []
						uni.showToast({
							title: '聊天已结束',
							icon: 'success'
						})
					}
				}
			})
		},
		
		// 获取头像文字
		getAvatarText(name) {
			if (!name) return '?'
			return name.charAt(0)
		},
		
		// 格式化时间
		formatTime(timestamp) {
			const now = new Date().getTime()
			const diff = now - timestamp
			
			if (diff < 60000) return '刚刚'
			if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
			if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
			if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
			
			const date = new Date(timestamp)
			return `${date.getMonth() + 1}/${date.getDate()}`
		},
		
		// 格式化消息时间（消息旁边显示的时间）
		formatMessageTime(timestamp) {
			const messageDate = new Date(timestamp)
			const now = new Date()
			
			// 清除时分秒，只比较日期
			const messageDateOnly = new Date(messageDate.getFullYear(), messageDate.getMonth(), messageDate.getDate())
			const todayDateOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate())
			
			// 计算时间差（天数）
			const diffTime = todayDateOnly - messageDateOnly
			const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
			
			const timeStr = `${String(messageDate.getHours()).padStart(2, '0')}:${String(messageDate.getMinutes()).padStart(2, '0')}`
			
			if (diffDays === 0) {
				// 今天，只显示时间
				return timeStr
			} else if (diffDays === 1) {
				// 昨天
				return `昨天 ${timeStr}`
			} else if (messageDate.getFullYear() === now.getFullYear()) {
				// 今年，显示月日
				return `${messageDate.getMonth() + 1}/${messageDate.getDate()} ${timeStr}`
			} else {
				// 更早，显示年月日
				return `${messageDate.getFullYear()}/${messageDate.getMonth() + 1}/${messageDate.getDate()} ${timeStr}`
			}
		},
		
	// 获取时间线文本（用于时间分隔线）
	getTimelineText(timestamp) {
		const messageDate = new Date(timestamp)
		const now = new Date()
		
		// 清除时分秒，只比较日期
		const messageDateOnly = new Date(messageDate.getFullYear(), messageDate.getMonth(), messageDate.getDate())
		const todayDateOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate())
		
		// 计算时间差（天数）
		const diffTime = todayDateOnly - messageDateOnly
		const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
		
		const timeStr = this.formatMessageTime(timestamp)
		
		if (diffDays === 0) {
			// 今天，只显示时间
			return timeStr
		} else if (diffDays === 1) {
			// 昨天
			return `昨天 ${timeStr}`
		} else if (diffDays < 7) {
			// 一周内，显示星期几
			const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
			return `${weekDays[messageDate.getDay()]} ${timeStr}`
		} else if (messageDate.getFullYear() === now.getFullYear()) {
			// 今年，显示月日
			return `${messageDate.getMonth() + 1}月${messageDate.getDate()}日 ${timeStr}`
		} else {
			// 更早，显示完整日期
			return `${messageDate.getFullYear()}年${messageDate.getMonth() + 1}月${messageDate.getDate()}日 ${timeStr}`
		}
	},
	
	// 格式化日期时间（用于用户资料）
	formatDateTime(timestamp) {
		if (!timestamp) return '未知'
		
		const date = new Date(timestamp)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')
		const seconds = String(date.getSeconds()).padStart(2, '0')
		
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
	},
		
		// 图片加载错误处理
		onImageError(e) {
			const imgElement = e.target || e.currentTarget
			const url = imgElement.dataset.url || imgElement.src
			console.error('图片加载失败:', {
				url: url,
				src: imgElement.src,
				dataset: imgElement.dataset
			})
			
			// 如果是 cloud:// 链接，尝试重新获取临时链接
			if (url && url.startsWith('cloud://')) {
				console.log('尝试重新获取云存储临时链接:', url)
				this.retryImageLoad(url, imgElement)
			} else if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
				// 如果是HTTP链接加载失败，可能是临时链接过期，尝试重新获取
				console.log('HTTP链接加载失败，尝试重新获取:', url)
				this.retryImageLoad(url, imgElement)
			} else {
				// 设置默认错误图片
				imgElement.src = '/static/images/image-error.png'
				console.log('设置默认错误图片')
			}
		},
		
		// 图片加载成功
		onImageLoad(e) {
			const url = e.target.dataset.url || e.currentTarget.dataset.url
			console.log('图片加载成功:', url)
			this.imageLoaded = true
		},
		
		// 重试图片加载
		async retryImageLoad(fileID, imgElement) {
			try {
				// 如果是云存储的fileID，获取临时访问链接
				if (fileID.startsWith('cloud://')) {
					const getTempUrlRes = await uniCloud.getTempFileURL({
						fileList: [fileID]
					})
					
					if (getTempUrlRes.fileList && getTempUrlRes.fileList.length > 0) {
						const newUrl = getTempUrlRes.fileList[0].tempFileURL
						if (newUrl && imgElement) {
							imgElement.src = newUrl
							console.log('重新获取云存储图片临时链接成功:', newUrl)
						}
					}
				} else if (fileID.startsWith('http://') || fileID.startsWith('https://')) {
					// 如果是HTTP链接，直接使用
					if (imgElement) {
						imgElement.src = fileID
						console.log('重新使用HTTP链接:', fileID)
					}
				} else {
					console.warn('未知的图片URL格式:', fileID)
				}
			} catch (error) {
				console.error('重新获取图片链接失败:', error)
				// 设置默认错误图片
				if (imgElement) {
					imgElement.src = '/static/images/image-error.png'
				}
			}
		},
		
		// 重试加载消息
		async retryLoadMessage(message) {
			if (!this.selectedUser) return
			
			uni.showLoading({
				title: '重新加载中...'
			})
			
			try {
				// 重新获取这条消息的详细信息
				const res = await uniCloud.callFunction({
					name: 'adminChat',
					data: {
						action: 'getMessages',
						userId: this.selectedUser.id,
						page: 1,
						pageSize: 50
					}
				})
				
				if (res.result && res.result.code === 200) {
					const newMessages = res.result.data
					
					// 找到对应的消息并更新
					const targetMessage = newMessages.find(msg => msg.id === message.id)
					if (targetMessage && targetMessage.content && targetMessage.content.trim()) {
						const index = this.messages.findIndex(m => m.id === message.id)
						if (index !== -1) {
							this.messages.splice(index, 1, targetMessage)
							uni.showToast({
								title: '重新加载成功',
								icon: 'success'
							})
						}
					} else {
						uni.showToast({
							title: '图片仍然无法加载',
							icon: 'none'
						})
					}
				} else {
					throw new Error('获取消息失败')
				}
			} catch (error) {
				console.error('重试加载消息失败:', error)
				uni.showToast({
					title: '重新加载失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		
		
		// 测试聊天隔离
		async testChatIsolation() {
			try {
				uni.showLoading({
					title: '测试中...'
				})
				
				const res = await uniCloud.callFunction({
					name: 'testChatMessageIsolation'
				})
				
				if (res.result && res.result.code === 200) {
					console.log('聊天隔离测试结果:', res.result.data)
					
					const stats = res.result.data.statistics
					const testResults = res.result.data.testResults
					
					let resultText = `📊 消息统计:\n`
					resultText += `总消息数: ${stats.total}\n`
					resultText += `客服消息: ${stats.customerServiceMessages}\n`
					resultText += `用户间消息: ${stats.userToUserMessages}\n`
					resultText += `有任务ID: ${stats.withTaskId}\n`
					resultText += `无任务ID: ${stats.withoutTaskId}\n\n`
					
					if (testResults.getChatMessages) {
						resultText += `🔍 getChatMessages测试:\n`
						resultText += `成功: ${testResults.getChatMessages.success ? '✅' : '❌'}\n`
						resultText += `消息数: ${testResults.getChatMessages.messageCount}\n`
						resultText += `包含客服消息: ${testResults.getChatMessages.hasCustomerServiceMessages ? '❌' : '✅'}\n\n`
					}
					
					if (testResults.getChatList) {
						resultText += `📋 getChatList测试:\n`
						resultText += `成功: ${testResults.getChatList.success ? '✅' : '❌'}\n`
						resultText += `聊天数: ${testResults.getChatList.chatCount}\n`
						resultText += `包含客服聊天: ${testResults.getChatList.hasAdminChats ? '❌' : '✅'}\n`
					}
					
					uni.showModal({
						title: '聊天隔离测试结果',
						content: resultText,
						showCancel: false
					})
				} else {
					throw new Error('测试失败')
				}
			} catch (error) {
				console.error('测试聊天隔离失败:', error)
				uni.showToast({
					title: '测试失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 预加载云存储图片的临时链接
		async preloadCloudImages() {
			const imageMessages = this.messages.filter(msg => 
				msg.type === 'image' && 
				msg.imageUrl && 
				msg.imageUrl.startsWith('cloud://')
			)
			
			if (imageMessages.length === 0) return
			
			try {
				const fileIDs = imageMessages.map(msg => msg.imageUrl)
				const getTempUrlRes = await uniCloud.getTempFileURL({
					fileList: fileIDs
				})
				
				if (getTempUrlRes.fileList && getTempUrlRes.fileList.length > 0) {
					// 将临时链接存储到消息对象中
					imageMessages.forEach((msg, index) => {
						const tempUrl = getTempUrlRes.fileList[index]?.tempFileURL
						if (tempUrl) {
							msg.tempImageUrl = tempUrl
							console.log('预加载云存储图片临时链接:', tempUrl)
						}
					})
				}
			} catch (error) {
				console.error('预加载云存储图片失败:', error)
			}
		},
		
	// 获取图片URL
	getImageUrl(message) {
		if (message.type === 'image') {
			console.log('获取图片URL:', message)
			// 优先使用预加载的临时链接
			if (message.tempImageUrl) {
				console.log('使用预加载的临时链接作为图片URL:', message.tempImageUrl)
				return message.tempImageUrl
			}
			
			// 然后使用 imageUrl 字段（存储的是云存储的fileID或临时URL）
			if (message.imageUrl && message.imageUrl.trim()) {
				console.log('使用imageUrl作为图片URL:', message.imageUrl)
				return message.imageUrl
			}
			
			// 然后使用 content 字段作为备用（云函数可能已将URL转换到content）
			if (message.content && 
				message.content !== '[图片]' && 
				message.content.trim()) {
				
				// 如果是云存储的fileID（cloud://开头），直接返回
				if (message.content.startsWith('cloud://')) {
					console.log('使用content中的云存储fileID作为图片URL:', message.content)
					return message.content
				}
				
				// 如果是HTTP/HTTPS URL，直接返回
				if (message.content.startsWith('http://') || message.content.startsWith('https://')) {
					console.log('使用content中的HTTP URL作为图片URL:', message.content)
					return message.content
				}
				
				// 如果是本地临时路径，说明是正在上传的图片
				if (message.content.startsWith('file://')) {
					console.log('使用content中的本地临时路径作为图片URL:', message.content)
					return message.content
				}
				
				// 如果content不是标准格式，可能是云存储的fileID但没有cloud://前缀
				// 这种情况下，我们需要将其转换为cloud://格式
				if (message.content && !message.content.includes('://')) {
					const cloudFileID = `cloud://${message.content}`
					console.log('转换content中的云存储fileID格式:', cloudFileID)
					return cloudFileID
				}
			}
			
			// 如果都没有有效URL，记录错误
			console.error('图片消息没有有效的URL:', {
				messageId: message.id,
				content: message.content,
				imageUrl: message.imageUrl,
				avatar: message.avatar
			})
		}
		return null
	},
	
	// ==================== 历史记录相关方法 ====================
	
	// 显示历史记录面板
	async showHistoryPanel() {
		if (!this.selectedUser) return
		
		this.showHistoryDrawer = true
		// 加载会话统计信息
		await this.loadMessageStatistics()
	},
	
	// 关闭历史记录面板
	async closeHistoryDrawer() {
		this.showHistoryDrawer = false
		// 清空筛选条件
		this.historySearchKeyword = ''
		this.historyStartDate = ''
		this.historyEndDate = ''
		this.historyMessageType = ''
		
		// 如果之前停止了实时更新，重新启动
		if (!this.userListTimer && this.selectedUser) {
			await this.loadChatMessages(this.selectedUser.id)
			this.startRealtimeUpdates()
		}
	},
	
	// ============= 快捷操作相关 =============
	
	// 加载用户统计数据（用于快捷操作）
	async loadUserStatistics() {
		if (!this.selectedUser) return
		
		try {
			// 使用 userPointsManager 云函数获取用户积分信息
			const res = await uniCloud.callFunction({
				name: 'userPointsManager',
				data: {
					action: 'getUserPoints'
				}
			})
			
			if (res.result && res.result.code === 0) {
				// 从返回的用户列表中找到当前用户
				const users = res.result.data || []
				const currentUserData = users.find(u => u._id === this.selectedUser.id)
				
				if (currentUserData) {
					this.userStatistics = {
						points: currentUserData.points || 0,
						creditScore: currentUserData.credit_score || 0,
						level_name: currentUserData.level_name || '新手'
					}
					console.log('✅ 加载用户统计成功:', this.userStatistics)
				} else {
					console.warn('未找到用户数据')
					// 设置默认值
					this.userStatistics = {
						points: 0,
						creditScore: 0,
						level_name: '新手'
					}
				}
			} else {
				console.error('加载用户统计失败:', res.result)
			}
		} catch (error) {
			console.error('加载用户统计失败:', error)
		}
	},
	
	// 显示快捷操作抽屉
	async showQuickActions() {
		if (!this.selectedUser) {
			uni.showToast({
				title: '请先选择用户',
				icon: 'none'
			})
			return
		}
		
		// 加载用户统计数据
		await this.loadUserStatistics()
		
		// 重置表单
		this.pointsAdjust = 0
		this.creditScoreAdjust = 0
		this.violationType = ''
		this.violationReason = ''
		
		this.showQuickActionsDrawer = true
	},
	
	// 关闭快捷操作抽屉
	closeQuickActionsDrawer() {
		this.showQuickActionsDrawer = false
	},
	
	// 提交积分调整
	async submitPointsAdjust() {
		if (!this.selectedUser) return
		
		if (this.pointsAdjust === 0) {
			uni.showToast({
				title: '请输入调整积分',
				icon: 'none'
			})
			return
		}
		
		uni.showModal({
			title: '确认调整积分',
			content: `确认为用户${this.pointsAdjust > 0 ? '增加' : '减少'}${Math.abs(this.pointsAdjust)}积分吗？`,
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({ title: '调整中...' })
					
					try {
						// 获取当前登录的管理员信息
						const userInfo = uni.getStorageSync('userInfo')
						const operator = userInfo ? (userInfo.nickname || userInfo.username || '管理员') : '客服'
						
						// 使用 userPointsManager 云函数调整积分
						const result = await uniCloud.callFunction({
							name: 'userPointsManager',
							data: {
								action: 'adjustUserPoints',
								userId: this.selectedUser.id,
								type: 'points',
								adjustAction: this.pointsAdjust > 0 ? 'add' : 'subtract',
								amount: Math.abs(this.pointsAdjust),
								reason: '客服调整',
								note: '客服快捷操作调整积分',
								operator: operator
							}
						})
						
						uni.hideLoading()
						
						console.log('积分调整结果:', result)
						
						if (result.result && result.result.code === 0) {
							uni.showToast({
								title: '积分调整成功',
								icon: 'success'
							})
							
							// 刷新用户统计
							await this.loadUserStatistics()
							this.pointsAdjust = 0
						} else {
							uni.showToast({
								title: result.result?.msg || '调整失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.hideLoading()
						console.error('[submitPointsAdjust] 错误:', error)
						uni.showToast({
							title: '调整失败: ' + (error.message || '未知错误'),
							icon: 'none'
						})
					}
				}
			}
		})
	},
	
	// 提交信用分调整
	async submitCreditScore() {
		if (!this.selectedUser) return
		
		if (this.creditScoreAdjust === 0) {
			uni.showToast({
				title: '请输入调整信用分',
				icon: 'none'
			})
			return
		}
		
		uni.showModal({
			title: '确认调整信用分',
			content: `确认为用户${this.creditScoreAdjust > 0 ? '增加' : '减少'}${Math.abs(this.creditScoreAdjust)}信用分吗？`,
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({ title: '调整中...' })
					
					try {
						// 获取当前登录的管理员信息
						const userInfo = uni.getStorageSync('userInfo')
						const operator = userInfo ? (userInfo.nickname || userInfo.username || '管理员') : '客服'
						
						// 使用 userPointsManager 云函数调整信用分
						const result = await uniCloud.callFunction({
							name: 'userPointsManager',
							data: {
								action: 'adjustUserPoints',
								userId: this.selectedUser.id,
								type: 'credit',
								adjustAction: this.creditScoreAdjust > 0 ? 'add' : 'subtract',
								amount: Math.abs(this.creditScoreAdjust),
								reason: '客服调整',
								note: '客服快捷操作调整信用分',
								operator: operator
							}
						})
						
						uni.hideLoading()
						
						console.log('信用分调整结果:', result)
						
						if (result.result && result.result.code === 0) {
							uni.showToast({
								title: '信用分调整成功',
								icon: 'success'
							})
							
							// 刷新用户统计
							await this.loadUserStatistics()
							this.creditScoreAdjust = 0
						} else {
							uni.showToast({
								title: result.result?.msg || '调整失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.hideLoading()
						console.error('[submitCreditScore] 错误:', error)
						uni.showToast({
							title: '调整失败: ' + (error.message || '未知错误'),
							icon: 'none'
						})
					}
				}
			}
		})
	},
	
	// 提交违规标记
	async submitViolation(actionType) {
		if (!this.selectedUser) return
		
		if (!this.violationType) {
			uni.showToast({
				title: '请选择违规类型',
				icon: 'none'
			})
			return
		}
		
		if (!this.violationReason || this.violationReason.trim() === '') {
			uni.showToast({
				title: '请输入违规原因',
				icon: 'none'
			})
			return
		}
		
		const actionText = actionType === 'ban' ? '禁用账号' : '警告用户'
		
		uni.showModal({
			title: `确认${actionText}`,
			content: `确认${actionText}吗？\n类型：${this.getViolationTypeName()}\n原因：${this.violationReason}`,
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({ title: '处理中...' })
					
					try {
						// 获取当前登录的管理员信息
						const userInfo = uni.getStorageSync('userInfo')
						const operator = userInfo ? (userInfo.nickname || userInfo.username || '管理员') : '客服'
						
						// 根据违规次数和类型确定扣除的信用分
						let deductAmount = 0
						if (actionType === 'ban') {
							// 禁用账号：清零信用分（扣除当前所有信用分）
							deductAmount = this.userStatistics?.creditScore || 100
						} else {
							// 警告：根据违规类型扣分
							const deductMap = {
								'spam': 10,      // 垃圾信息扣10分
								'fraud': 30,     // 欺诈行为扣30分
								'abuse': 20,     // 恶意骚扰扣20分
								'other': 15      // 其他违规扣15分
							}
							deductAmount = deductMap[this.violationType] || 10
						}
						
						// 使用 userPointsManager 云函数调整信用分
						const result = await uniCloud.callFunction({
							name: 'userPointsManager',
							data: {
								action: 'adjustUserPoints',
								userId: this.selectedUser.id,
								type: 'credit',
								adjustAction: 'subtract',
								amount: deductAmount,
								reason: `违规处理-${this.getViolationTypeName()}`,
								note: `${actionText}：${this.violationReason}`,
								operator: operator
							}
						})
						
						uni.hideLoading()
						
						console.log('违规处理结果:', result)
						
						if (result.result && result.result.code === 0) {
							uni.showToast({
								title: `处理成功，已扣除${deductAmount}信用分`,
								icon: 'success',
								duration: 2000
							})
							
							// 重置表单
							this.violationType = ''
							this.violationReason = ''
							
							// 刷新用户统计
							await this.loadUserStatistics()
							
							// 如果是禁用账号，可能需要结束会话
							if (actionType === 'ban') {
								setTimeout(() => {
									this.closeQuickActionsDrawer()
									this.endChat()
								}, 2000)
							}
						} else {
							uni.showToast({
								title: result.result?.msg || '处理失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.hideLoading()
						console.error('[submitViolation] 错误:', error)
						uni.showToast({
							title: '处理失败: ' + (error.message || '未知错误'),
							icon: 'none'
						})
					}
				}
			}
		})
	},
	
	// 获取违规类型名称
	getViolationTypeName() {
		const types = {
			spam: '垃圾信息',
			fraud: '欺诈行为',
			abuse: '恶意骚扰',
			other: '其他违规'
		}
		return types[this.violationType] || '未知'
	},
	
	// 加载更多历史消息（向上滚动）
	async loadMoreHistoryMessages() {
		if (!this.selectedUser || this.isLoadingMore || !this.hasMoreHistory) return
		
		console.log('[loadMoreHistoryMessages] 开始加载更多历史消息')
		this.isLoadingMore = true
		
		try {
			// 获取当前最早的消息时间
			const oldestMessage = this.messages[0]
			if (!oldestMessage) {
				this.hasMoreHistory = false
				return
			}
			
			const beforeTime = oldestMessage.createTime
			
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'getMessages',
					userId: this.selectedUser.id,
					page: 1,
					pageSize: 20,
					beforeTime: beforeTime
				}
			})
			
			if (res.result.code === 200) {
				const newMessages = res.result.data || []
				console.log('[loadMoreHistoryMessages] 加载到', newMessages.length, '条历史消息')
				
				if (newMessages.length === 0) {
					this.hasMoreHistory = false
					uni.showToast({
						title: '没有更多消息了',
						icon: 'none',
						duration: 1500
					})
				} else {
					// 将新消息添加到现有消息列表的前面
					this.messages = [...newMessages, ...this.messages]
					
					// 如果返回的消息少于请求数量，说明已经没有更多了
					if (newMessages.length < 20) {
						this.hasMoreHistory = false
					}
				}
			}
		} catch (error) {
			console.error('[loadMoreHistoryMessages] 加载历史消息失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			this.isLoadingMore = false
		}
	},
	
	// 加载会话统计信息
	async loadMessageStatistics() {
		if (!this.selectedUser) return
		
		this.isLoadingStatistics = true
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'getMessageStatistics',
					userId: this.selectedUser.id
				}
			})
			
			if (res.result && res.result.code === 200) {
				this.messageStatistics = res.result.data
				console.log('[loadMessageStatistics] 统计信息:', this.messageStatistics)
			} else {
				console.error('[loadMessageStatistics] 获取统计失败:', res.result.msg)
			}
		} catch (error) {
			console.error('[loadMessageStatistics] 获取统计失败:', error)
		} finally {
			this.isLoadingStatistics = false
		}
	},
	
	// 搜索历史消息
	async searchHistoryMessages() {
		if (!this.selectedUser) return
		
		uni.showLoading({
			title: '搜索中...'
		})
		
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'searchMessages',
					userId: this.selectedUser.id,
					keyword: this.historySearchKeyword,
					startDate: this.historyStartDate,
					endDate: this.historyEndDate,
					messageType: this.historyMessageType || null,
					page: 1,
					pageSize: 100
				}
			})
			
			if (res.result && res.result.code === 200) {
				const searchResult = res.result.data
				console.log('[searchHistoryMessages] 搜索结果:', searchResult)
				
				// 将搜索结果显示在主聊天区域
				this.messages = searchResult.messages || []
				
				// 关闭抽屉
				this.showHistoryDrawer = false
				
				// 停止实时更新（避免搜索结果被覆盖）
				this.stopRealtimeUpdates()
				
				uni.showToast({
					title: `找到 ${searchResult.total} 条消息`,
					icon: 'success',
					duration: 2000
				})
				
				// 滚动到顶部显示搜索结果
				this.$nextTick(() => {
					this.scrollTop = 0
				})
			} else {
				throw new Error(res.result ? res.result.msg : '搜索失败')
			}
		} catch (error) {
			console.error('[searchHistoryMessages] 搜索失败:', error)
			uni.showToast({
				title: '搜索失败: ' + error.message,
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	},
	
	// 搜索输入事件
	onSearchInput(e) {
		console.log('搜索输入:', e.detail.value)
		this.historySearchKeyword = e.detail.value
	},
	
	// 日期选择器事件
	onStartDateChange(e) {
		this.historyStartDate = e.detail.value
	},
	
	onEndDateChange(e) {
		this.historyEndDate = e.detail.value
	},
	
	// 设置快捷日期范围
	setQuickDateRange(range) {
		const today = new Date()
		const endDate = today.toISOString().split('T')[0]
		
		let startDate = ''
		switch (range) {
			case 'today':
				startDate = endDate
				break
			case 'yesterday':
				const yesterday = new Date(today)
				yesterday.setDate(yesterday.getDate() - 1)
				startDate = yesterday.toISOString().split('T')[0]
				this.historyEndDate = startDate
				break
			case 'week':
				const weekAgo = new Date(today)
				weekAgo.setDate(weekAgo.getDate() - 7)
				startDate = weekAgo.toISOString().split('T')[0]
				break
			case 'month':
				const monthAgo = new Date(today)
				monthAgo.setDate(monthAgo.getDate() - 30)
				startDate = monthAgo.toISOString().split('T')[0]
				break
		}
		
		this.historyStartDate = startDate
		if (range !== 'yesterday') {
			this.historyEndDate = endDate
		}
		
		// 自动搜索
		this.searchHistoryMessages()
	},
	
	// 清除筛选条件
	async clearFilters() {
		this.historySearchKeyword = ''
		this.historyStartDate = ''
		this.historyEndDate = ''
		this.historyMessageType = ''
		
		// 关闭抽屉
		this.showHistoryDrawer = false
		
		// 重新加载当前会话的所有消息
		if (this.selectedUser) {
			await this.loadChatMessages(this.selectedUser.id)
			
			// 重新启动实时更新
			this.startRealtimeUpdates()
			
			uni.showToast({
				title: '已清除筛选',
				icon: 'success',
				duration: 1500
			})
			
			// 滚动到底部
			this.$nextTick(() => {
				setTimeout(() => {
					this.scrollToBottom()
				}, 200)
			})
		}
	},
	
	// 导出聊天记录
	async exportChatHistory(format) {
		if (!this.selectedUser) return
		
		uni.showLoading({
			title: '正在导出...'
		})
		
		try {
			const res = await uniCloud.callFunction({
				name: 'adminChat',
				data: {
					action: 'exportMessages',
					userId: this.selectedUser.id,
					format: format,
					startDate: this.historyStartDate || null,
					endDate: this.historyEndDate || null
				}
			})
			
			if (res.result && res.result.code === 200) {
				const exportData = res.result.data
				
				if (!exportData.content) {
					uni.showToast({
						title: '没有可导出的消息',
						icon: 'none'
					})
					return
				}
				
				// 创建下载链接（H5环境）
				// #ifdef H5
				const blob = new Blob([exportData.content], { 
					type: format === 'json' ? 'application/json' : 'text/plain' 
				})
				const url = URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = exportData.filename
				document.body.appendChild(a)
				a.click()
				document.body.removeChild(a)
				URL.revokeObjectURL(url)
				
				uni.showToast({
					title: '导出成功',
					icon: 'success'
				})
				// #endif
				
				// 非H5环境提示
				// #ifndef H5
				uni.showModal({
					title: '导出内容',
					content: '导出功能在H5环境下可直接下载文件。当前环境请复制以下内容保存：\n\n' + exportData.content.substring(0, 200) + '...',
					showCancel: true,
					cancelText: '关闭',
					confirmText: '复制',
					success: (modalRes) => {
						if (modalRes.confirm) {
							uni.setClipboardData({
								data: exportData.content,
								success: () => {
									uni.showToast({
										title: '已复制到剪贴板',
										icon: 'success'
									})
								}
							})
						}
					}
				})
				// #endif
			} else {
				throw new Error(res.result ? res.result.msg : '导出失败')
			}
		} catch (error) {
			console.error('[exportChatHistory] 导出失败:', error)
			uni.showToast({
				title: '导出失败: ' + error.message,
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	}
}
</script>

<style scoped>
/* 主容器 */
.chat-page {
	height: calc(100vh - 124rpx);
	background: #f8fafc;
}

.chat-container {
	display: flex;
	height: 100%;
	background: #fff;
	border-radius: 8rpx;
	overflow: hidden;
	border: 1rpx solid #e8e8e8;
}

/* 左侧边栏 */
.chat-sidebar {
	width: 480rpx;
	border-right: 2rpx solid #f0f0f0;
	display: flex;
	flex-direction: column;
	background: #fafafa;
}

/* 搜索栏 */
.search-bar {
	padding: 24rpx;
	border-bottom: 2rpx solid #f0f0f0;
	background: #fff;
}

.search-input-wrapper {
	position: relative;
	display: flex;
	align-items: center;
	background: #f8fafc;
	border-radius: 12rpx;
	padding: 0 16rpx;
	border: 2rpx solid #e2e8f0;
	transition: all 0.3s ease;
}

.search-input-wrapper:focus-within {
	border-color: #1890ff;
	background: #fff;
}

.search-icon {
	font-size: 28rpx;
	color: #9ca3af;
	margin-right: 12rpx;
}

.search-input {
	flex: 1;
	padding: 16rpx 0;
	font-size: 28rpx;
	color: #374151;
	background: transparent;
	border: none;
}

.clear-btn {
	font-size: 24rpx;
	color: #9ca3af;
	padding: 8rpx;
	cursor: pointer;
}

/* 筛选标签 */
.filter-tabs {
	display: flex;
	padding: 16rpx 24rpx;
	gap: 8rpx;
	background: #fff;
	border-bottom: 2rpx solid #f0f0f0;
}

.filter-tab {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 16rpx;
	background: #f5f5f5;
	border-radius: 6rpx;
	cursor: pointer;
	transition: background 0.2s ease;
	position: relative;
}

.filter-tab.active {
	background: #1890ff;
	color: #fff;
}

.filter-text {
	font-size: 26rpx;
	font-weight: 500;
}

.filter-badge {
	min-width: 32rpx;
	height: 32rpx;
	padding: 0 8rpx;
	background: #e53e3e;
	color: #fff;
	font-size: 20rpx;
	font-weight: 600;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.filter-tab.active .filter-badge {
	background: rgba(255, 255, 255, 0.3);
}

/* 用户列表 */
.user-list {
	flex: 1;
	padding: 16rpx 0;
}

.user-item {
	display: flex;
	align-items: center;
	gap: 20rpx;
	padding: 16rpx 20rpx;
	margin: 4rpx 12rpx;
	border-radius: 8rpx;
	cursor: pointer;
	transition: background 0.2s ease;
	position: relative;
	background: #fff;
}

.user-item:hover {
	background: #f5f5f5;
}

.user-item.active {
	background: #1890ff;
	color: #fff;
}

.user-item.unread::before {
	content: '';
	position: absolute;
	left: 8rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 6rpx;
	height: 6rpx;
	background: #e53e3e;
	border-radius: 50%;
}

/* 用户头像 */
.user-avatar {
	position: relative;
	width: 80rpx;
	height: 80rpx;
	flex-shrink: 0;
}

.avatar-img {
	width: 100%;
	height: 100%;
	border-radius: 50%;
}

.avatar-placeholder {
	width: 100%;
	height: 100%;
	background: #95de64;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.avatar-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #fff;
}

.online-dot {
	position: absolute;
	bottom: 4rpx;
	right: 4rpx;
	width: 16rpx;
	height: 16rpx;
	background: #52c41a;
	border: 2rpx solid #fff;
	border-radius: 50%;
}

/* 用户信息 */
.user-info {
	flex: 1;
	min-width: 0;
}

.user-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.user-nickname {
	font-size: 30rpx;
	font-weight: 600;
	color: inherit;
}

.last-time {
	font-size: 22rpx;
	color: #9ca3af;
}

.user-item.active .last-time {
	color: rgba(255, 255, 255, 0.8);
}

.user-message {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.message-preview {
	font-size: 26rpx;
	color: #6b7280;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	flex: 1;
}

.user-item.active .message-preview {
	color: rgba(255, 255, 255, 0.9);
}

.unread-badge {
	min-width: 32rpx;
	height: 32rpx;
	padding: 0 8rpx;
	background: #e53e3e;
	color: #fff;
	font-size: 20rpx;
	font-weight: 600;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-left: 12rpx;
}


/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx 40rpx;
	color: #9ca3af;
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 24rpx;
}

.empty-text {
	font-size: 28rpx;
}

/* 右侧聊天区域 */
.chat-main {
	flex: 1;
	display: flex;
	flex-direction: column;
	background: #fff;
}

/* 聊天头部 */
.chat-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 32rpx;
	border-bottom: 2rpx solid #f0f0f0;
	background: #fff;
}

.chat-user-info {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.chat-avatar {
	position: relative;
	width: 80rpx;
	height: 80rpx;
}

.chat-user-details {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.user-name-row {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.chat-user-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #1f2937;
}

.user-status {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 6rpx 12rpx;
	background: #f3f4f6;
	border-radius: 8rpx;
}

.user-status.online {
	background: #f6ffed;
	color: #52c41a;
}

.status-dot {
	width: 12rpx;
	height: 12rpx;
	background: #9ca3af;
	border-radius: 50%;
}

.user-status.online .status-dot {
	background: #52c41a;
}

.status-text {
	font-size: 22rpx;
	font-weight: 500;
}

.chat-user-id {
	font-size: 24rpx;
	color: #6b7280;
}

/* 聊天操作按钮 */
.chat-actions {
	display: flex;
	gap: 12rpx;
}

.action-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 16rpx;
	background: #fff;
	border: 1rpx solid #d9d9d9;
	border-radius: 6rpx;
	cursor: pointer;
	transition: all 0.2s ease;
	font-size: 24rpx;
	color: #666;
}

.action-btn:hover {
	background: #f5f5f5;
	border-color: #b3b3b3;
}

.action-btn.danger {
	color: #ff4d4f;
}

.action-btn.danger:hover {
	background: #fff2f0;
	border-color: #ffccc7;
}

.action-btn .iconfont {
	font-size: 28rpx;
}

.btn-text {
	font-size: 24rpx;
	font-weight: 400;
}

/* 聊天内容区域 */
.chat-content {
	flex: 1;
	position: relative;
	overflow: hidden;
}

.message-list {
	height: 100%;
	padding: 24rpx;
}

/* 搜索结果提示条 */
.search-result-tip {
	position: sticky;
	top: 0;
	z-index: 10;
	background: linear-gradient(135deg, #fff7e6 0%, #fffbf0 100%);
	border-bottom: 2rpx solid #ffd591;
	animation: slideDown 0.3s ease;
}

.tip-content {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 16rpx 24rpx;
}

.tip-icon {
	font-size: 28rpx;
	color: #fa8c16;
}

.tip-text {
	font-size: 26rpx;
	color: #d46b08;
	font-weight: 500;
}

.tip-btn {
	display: flex;
	align-items: center;
	gap: 6rpx;
	padding: 8rpx 16rpx;
	margin-left: 16rpx;
	background: #fff;
	border: 1rpx solid #ffd591;
	border-radius: 6rpx;
	font-size: 24rpx;
	color: #d46b08;
	cursor: pointer;
	transition: all 0.2s ease;
}

.tip-btn:hover {
	background: #ffd591;
	color: #fff;
}

.tip-btn .iconfont {
	font-size: 22rpx;
}

.load-more {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 20rpx;
	color: #1890ff;
	cursor: pointer;
	font-size: 26rpx;
}

.load-icon {
	font-size: 28rpx;
}

/* 时间分隔线 */
.time-divider {
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 40rpx 0 32rpx 0;
	padding: 0 40rpx;
	gap: 20rpx;
}

.time-divider-line {
	flex: 1;
	height: 1rpx;
	background: linear-gradient(90deg, transparent, #d1d5db, transparent);
	opacity: 0.6;
}

.time-divider-text {
	font-size: 22rpx;
	color: #6b7280;
	padding: 8rpx 20rpx;
	background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
	border-radius: 24rpx;
	white-space: nowrap;
	font-weight: 500;
	border: 1rpx solid #e2e8f0;
	box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.05);
	letter-spacing: 0.5rpx;
}

/* 消息项 */
.message-item {
	display: flex;
	margin-bottom: 32rpx;
}

.message-item.message-right {
	flex-direction: row-reverse;
}

.message-item.message-right .message-content {
	align-items: flex-end;
}

.message-item.message-right .message-header {
	flex-direction: row-reverse;
}

.message-item.message-right .message-bubble {
	background: #1890ff;
	color: #fff;
}

.message-avatar {
	width: 64rpx;
	height: 64rpx;
	margin: 0 16rpx;
	flex-shrink: 0;
}

.message-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	max-width: 70%;
}

.message-header {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 8rpx;
}

.sender-name {
	font-size: 24rpx;
	color: #6b7280;
	font-weight: 500;
}

.message-time {
	font-size: 22rpx;
	color: #9ca3af;
}

/* 消息气泡 */
.message-bubble {
	padding: 16rpx 20rpx;
	border-radius: 20rpx;
	background: #f8fafc;
	border: 2rpx solid #e5e7eb;
	position: relative;
	word-break: break-word;
	max-width: 100%;
}

.text-message .message-text {
	font-size: 28rpx;
	line-height: 1.5;
	white-space: pre-wrap;
}

.image-message {
	padding: 8rpx;
	background: transparent;
	border: none;
}

.message-image {
	max-width: 400rpx;
	max-height: 300rpx;
	border-radius: 12rpx;
}

.image-container {
	position: relative;
	overflow: hidden;
	border-radius: 12rpx;
}

.image-error {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	min-height: 120rpx;
	padding: 20rpx;
	background: #f5f5f5;
	border-radius: 12rpx;
	color: #999;
}

.error-icon {
	font-size: 48rpx;
	margin-bottom: 8rpx;
	color: #ccc;
}

.error-text {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 8rpx;
}

.retry-text {
	font-size: 22rpx;
	color: #1890ff;
	cursor: pointer;
	padding: 4rpx 8rpx;
	border-radius: 4rpx;
	background: rgba(24, 144, 255, 0.1);
}

.system-message {
	align-self: center;
	background: #f3f4f6;
	color: #6b7280;
	padding: 12rpx 24rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	margin: 16rpx 0;
}

.system-text {
	font-size: 24rpx;
}

/* 消息状态 */
.message-status {
	margin-top: 8rpx;
	align-self: flex-end;
}

.status-text {
	font-size: 22rpx;
	color: #9ca3af;
}

.status-text.sending {
	color: #f59e0b;
}

.status-text.sent {
	color: #10b981;
}

.status-text.read {
	color: #1890ff;
}

.status-text.failed {
	color: #e53e3e;
	cursor: pointer;
}

/* 空消息状态 */
.empty-messages {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
	color: #9ca3af;
}

.empty-chat-icon {
	font-size: 120rpx;
	margin-bottom: 32rpx;
}

.empty-chat-text {
	font-size: 32rpx;
}

/* 未选择聊天状态 */
.no-chat-selected {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
	color: #9ca3af;
}

.no-chat-icon {
	font-size: 160rpx;
	margin-bottom: 32rpx;
}

.no-chat-title {
	font-size: 40rpx;
	font-weight: 600;
	margin-bottom: 16rpx;
	color: #4b5563;
}

.no-chat-desc {
	font-size: 28rpx;
}

/* 消息输入区域 */
.chat-input-area {
	border-top: 2rpx solid #f0f0f0;
	background: #fff;
}

/* 快捷回复 */
.quick-replies {
	padding: 16rpx 24rpx;
	border-bottom: 2rpx solid #f0f0f0;
	background: #f8fafc;
}

.quick-reply-list {
	white-space: nowrap;
}

.quick-reply-item {
	display: inline-block;
	padding: 12rpx 20rpx;
	margin-right: 16rpx;
	background: #fff;
	border: 2rpx solid #e5e7eb;
	border-radius: 20rpx;
	font-size: 26rpx;
	color: #374151;
	cursor: pointer;
	transition: all 0.3s ease;
}

.quick-reply-item:hover {
	background: #f0f0f0;
	border-color: #d9d9d9;
}

/* 输入工具栏 */
.input-toolbar {
	display: flex;
	gap: 16rpx;
	padding: 16rpx 24rpx;
	background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
	border-bottom: 1rpx solid #e2e8f0;
}

.toolbar-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 12rpx 20rpx;
	background: #fff;
	border: 1rpx solid #e2e8f0;
	border-radius: 8rpx;
	cursor: pointer;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	font-size: 26rpx;
	color: #64748b;
	box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
	position: relative;
	overflow: hidden;
}

.toolbar-btn::before {
	content: '';
	position: absolute;
	top: 0;
	left: -100%;
	width: 100%;
	height: 100%;
	background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
	transition: left 0.5s ease;
}

.toolbar-btn:hover::before {
	left: 100%;
}

.toolbar-btn:hover {
	background: #f8fafc;
	border-color: #cbd5e1;
	transform: translateY(-1rpx);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.toolbar-btn.active {
	background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
	color: #fff;
	border-color: #3b82f6;
	box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.4);
}

.toolbar-btn.active::before {
	display: none;
}

.toolbar-icon {
	font-size: 28rpx;
	line-height: 1;
}

.toolbar-text {
	font-size: 26rpx;
	font-weight: 500;
	white-space: nowrap;
}

.quick-btn:hover {
	border-color: #3b82f6;
	color: #3b82f6;
}

.image-btn:hover {
	border-color: #10b981;
	color: #10b981;
}

/* 消息输入容器 */
.message-input-container {
	display: flex;
	align-items: flex-end;
	gap: 16rpx;
	padding: 24rpx;
}

.message-input {
	flex: 1;
	min-height: 80rpx;
	max-height: 240rpx;
	padding: 20rpx;
	background: #f8fafc;
	border: 2rpx solid #e5e7eb;
	border-radius: 16rpx;
	font-size: 28rpx;
	line-height: 1.5;
	resize: none;
	transition: all 0.3s ease;
}

.message-input:focus {
	background: #fff;
	border-color: #1890ff;
	outline: none;
}

.send-btn {
	height: 80rpx;
	padding: 0 24rpx;
	background: #f5f5f5;
	border: 1rpx solid #d9d9d9;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	overflow: hidden;
	min-width: 120rpx;
}

.send-btn::before {
	content: '';
	position: absolute;
	top: 0;
	left: -100%;
	width: 100%;
	height: 100%;
	background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
	transition: left 0.6s ease;
}

.send-btn:hover::before {
	left: 100%;
}

.send-btn:hover {
	background: #f0f0f0;
	border-color: #b3b3b3;
	transform: translateY(-1rpx);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.send-btn.active {
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
	color: #fff;
	border-color: #1890ff;
	box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.4);
}

.send-btn.active::before {
	display: none;
}

.send-btn.active:hover {
	background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
	transform: translateY(-2rpx);
	box-shadow: 0 6rpx 20rpx rgba(24, 144, 255, 0.5);
}

.send-btn.loading {
	pointer-events: none;
}

.send-btn:disabled {
	opacity: 0.6;
	cursor: not-allowed;
	transform: none;
	box-shadow: none;
}

.send-btn:disabled::before {
	display: none;
}

.send-btn-content {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.send-text {
	font-size: 28rpx;
	font-weight: 500;
	white-space: nowrap;
}

.send-icon-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32rpx;
	height: 32rpx;
}

.send-icon {
	font-size: 28rpx;
	line-height: 1;
}

.rotating {
	animation: rotate 1s linear infinite;
}

/* 输入提示 */
.input-tips {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12rpx 24rpx;
	background: #f8fafc;
	border-top: 2rpx solid #f0f0f0;
}

.tip-text {
	font-size: 22rpx;
	color: #9ca3af;
}

.typing-indicator {
	font-size: 22rpx;
	color: #1890ff;
	font-style: italic;
}

/* 动画 */

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

@keyframes slideDown {
	from {
		opacity: 0;
		transform: translateY(-20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

/* 响应式设计 */
@media (max-width: 1200px) {
	.chat-sidebar {
		width: 400rpx;
	}
}

@media (max-width: 900px) {
	.chat-container {
		flex-direction: column;
	}
	
	.chat-sidebar {
		width: 100%;
		height: 40%;
		border-right: none;
		border-bottom: 2rpx solid #f0f0f0;
	}
	
	.chat-main {
		height: 60%;
	}
	
	.chat-actions {
		flex-wrap: wrap;
	}
	
	.action-btn {
		min-width: 80rpx;
		padding: 12rpx 16rpx;
	}
}

/* 滚动条样式 */
::-webkit-scrollbar {
	width: 8rpx;
}

::-webkit-scrollbar-track {
	background: #f1f1f1;
	border-radius: 4rpx;
}

::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 4rpx;
}

::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
}

/* 抽屉样式 */
.drawer-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.3);
	z-index: 999;
	animation: fadeIn 0.3s ease;
	backdrop-filter: blur(2px);
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

.drawer-container {
	position: fixed;
	top: 0;
	right: -600rpx;
	width: 600rpx;
	height: 100vh;
	background: #fff;
	box-shadow: -4rpx 0 16rpx rgba(0, 0, 0, 0.1);
	z-index: 1000;
	display: flex;
	flex-direction: column;
	transition: right 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.drawer-container.drawer-show {
	right: 0;
}

.drawer-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 32rpx 40rpx;
	border-bottom: 2rpx solid #f0f0f0;
	background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
}

.drawer-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #1f2937;
}

.drawer-close {
	font-size: 36rpx;
	color: #9ca3af;
	cursor: pointer;
	padding: 8rpx;
	transition: all 0.2s ease;
}

.drawer-close:hover {
	color: #1f2937;
	transform: rotate(90deg);
}

.drawer-content {
	flex: 1;
	overflow-y: auto;
}

.drawer-loading {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
	color: #9ca3af;
}

.loading-text {
	margin-top: 16rpx;
	font-size: 28rpx;
}

/* 用户资料样式 */
.profile-section {
	padding: 40rpx;
}

.profile-avatar-section {
	display: flex;
	justify-content: center;
	margin-bottom: 48rpx;
}

.profile-avatar-wrapper {
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 16rpx;
}

.profile-avatar-img,
.profile-avatar-placeholder {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	border: 4rpx solid #f0f0f0;
}

.profile-avatar-placeholder {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
}

.profile-avatar-text {
	font-size: 64rpx;
	font-weight: 600;
	color: #fff;
}

.profile-online-badge {
	padding: 8rpx 20rpx;
	background: linear-gradient(135deg, #10b981 0%, #059669 100%);
	color: #fff;
	border-radius: 24rpx;
	font-size: 24rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
}

.profile-info-list {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.profile-info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx;
	background: #f8fafc;
	border-radius: 12rpx;
	border: 1rpx solid #e5e7eb;
	transition: all 0.2s ease;
}

.profile-info-item:hover {
	background: #f1f5f9;
	border-color: #cbd5e1;
	transform: translateX(-4rpx);
	box-shadow: 4rpx 0 12rpx rgba(0, 0, 0, 0.05);
}

.info-label {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.info-icon {
	font-size: 32rpx;
	color: #6b7280;
}

.info-label-text {
	font-size: 28rpx;
	color: #6b7280;
	font-weight: 500;
}

.info-value {
	font-size: 28rpx;
	color: #1f2937;
	font-weight: 600;
}

.info-value.status-active {
	color: #10b981;
}

.info-value.status-banned {
	color: #ef4444;
}

/* 用户统计样式 */
.statistics-section {
	padding: 40rpx;
}

.statistics-cards {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 24rpx;
	margin-bottom: 48rpx;
}

.stat-card {
	padding: 32rpx;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	gap: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
}

.stat-card:hover {
	transform: translateY(-4rpx);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
}

.stat-card-blue {
	background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
}

.stat-card-green {
	background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.stat-card-orange {
	background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.stat-card-purple {
	background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
}

.stat-icon-wrapper {
	width: 72rpx;
	height: 72rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.stat-card-icon {
	font-size: 36rpx;
	color: #fff;
}

.stat-info {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.stat-value {
	font-size: 40rpx;
	font-weight: 700;
	color: #fff;
	line-height: 1.2;
}

.stat-label {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.9);
	font-weight: 500;
}

/* 历史记录抽屉特殊样式 */
.history-drawer {
	width: 800rpx;
	right: -800rpx;
}

.history-drawer .drawer-content {
	position: relative;
	z-index: 1;
}

.history-drawer input {
	pointer-events: auto !important;
	-webkit-user-select: auto;
	user-select: auto;
}

/* 新的搜索输入框样式（简化版） */
.search-input-wrapper-new {
	display: flex;
	align-items: stretch;
	background: #fff;
	border: 2rpx solid #d9d9d9;
	border-radius: 8rpx;
	overflow: hidden;
	height: 80rpx;
}

.search-input-new {
	flex: 1;
	padding: 0 16rpx;
	font-size: 28rpx;
	color: #333;
	background: #fff;
	border: none;
	outline: none;
	line-height: 80rpx;
	height: 80rpx;
	box-sizing: border-box;
}

.search-input-new::placeholder {
	color: #999;
}

.search-btn-new {
	width: 120rpx;
	height: 80rpx;
	background: #1890ff;
	color: #fff;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: background 0.3s;
}

.search-btn-new:hover {
	background: #40a9ff;
}

.search-btn-new .iconfont {
	font-size: 32rpx;
	color: #fff;
}

.history-statistics {
	padding: 32rpx;
	background: linear-gradient(135deg, #f0f4f8 0%, #e8eef5 100%);
	margin: 24rpx;
	border-radius: 16rpx;
	color: #333;
	border: 1rpx solid #d9e2ec;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.stat-title {
	font-size: 32rpx;
	font-weight: 600;
	margin-bottom: 24rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #999;
	font-weight: 400;
}

.stat-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 16rpx;
	margin-bottom: 24rpx;
}

.stat-item {
	text-align: center;
	background: rgba(255, 255, 255, 0.8);
	padding: 20rpx;
	border-radius: 12rpx;
	border: 1rpx solid rgba(0, 0, 0, 0.06);
}

.stat-num {
	display: block;
	font-size: 36rpx;
	font-weight: 700;
	margin-bottom: 8rpx;
	color: #1890ff;
}

.stat-time-info {
	background: rgba(255, 255, 255, 0.6);
	padding: 16rpx;
	border-radius: 8rpx;
	border: 1rpx solid rgba(0, 0, 0, 0.06);
}

.time-info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8rpx 0;
	font-size: 24rpx;
}

.time-label {
	color: #666;
}

.time-value {
	color: #333;
	font-weight: 500;
}

/* 搜索和筛选区域 */
.history-search-section {
	padding: 32rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.search-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 24rpx;
}

.search-field,
.date-field {
	margin-bottom: 24rpx;
}

.field-label {
	display: block;
	font-size: 28rpx;
	color: #6b7280;
	margin-bottom: 12rpx;
	font-weight: 500;
}

.search-input-wrapper {
	display: flex;
	align-items: center;
	gap: 12rpx;
	background: #f8fafc;
	border: 2rpx solid #e5e7eb;
	border-radius: 12rpx;
	padding: 0 16rpx;
}

.search-input-wrapper .search-input {
	flex: 1;
	padding: 20rpx 0;
	font-size: 28rpx;
	background: transparent;
	border: none;
	outline: none;
	position: relative;
	z-index: 1;
}

.history-search-section .search-input-wrapper .search-input {
	pointer-events: auto;
}

.search-btn {
	padding: 16rpx 24rpx;
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
	border: none;
	border-radius: 8rpx;
	color: #fff;
	font-size: 28rpx;
}

.date-filter-section {
	display: flex;
	gap: 16rpx;
	margin-bottom: 24rpx;
}

.date-field {
	flex: 1;
}

.date-picker {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 16rpx;
	background: #f8fafc;
	border: 2rpx solid #e5e7eb;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #374151;
}

.date-text {
	color: #6b7280;
}

.type-filter-section,
.quick-date-section {
	margin-bottom: 16rpx;
}

.type-buttons,
.quick-date-buttons {
	display: flex;
	flex-wrap: wrap;
	gap: 8rpx;
	margin-top: 8rpx;
}

.type-btn,
.quick-date-btn {
	padding: 10rpx 20rpx;
	background: #fff;
	border: 1rpx solid #d9d9d9;
	border-radius: 6rpx;
	font-size: 24rpx;
	color: #666;
	transition: all 0.3s ease;
	box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
}

.type-btn.active {
	background: #e6f7ff;
	color: #1890ff;
	border-color: #91d5ff;
	font-weight: 500;
}

.type-btn:hover,
.quick-date-btn:hover {
	background: #fafafa;
	border-color: #40a9ff;
	color: #1890ff;
	transform: translateY(-1rpx);
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

/* 清除筛选按钮特殊样式 */
.quick-filter-row .quick-date-btn:last-child {
	color: #666;
	border-color: #d9d9d9;
}

.quick-filter-row .quick-date-btn:last-child:hover {
	color: #ff4d4f;
	border-color: #ff7875;
	background: #fff1f0;
}

/* 导出区域 */
.export-section {
	padding: 32rpx;
	display: flex;
	gap: 16rpx;
	border-top: 2rpx solid #f0f0f0;
}

.export-btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 24rpx;
	background: linear-gradient(135deg, #10b981 0%, #059669 100%);
	border: none;
	border-radius: 12rpx;
	color: #fff;
	font-size: 28rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
	transition: all 0.3s ease;
}

.export-btn:hover {
	transform: translateY(-2rpx);
	box-shadow: 0 6rpx 16rpx rgba(16, 185, 129, 0.4);
}

.export-btn .iconfont {
	font-size: 32rpx;
}

/* 操作按钮primary样式 */
.action-btn.primary {
	color: #1890ff;
	border-color: #1890ff;
}

.action-btn.primary:hover {
	background: #e6f7ff;
	border-color: #40a9ff;
}

/* 操作按钮warning样式 */
.action-btn.warning {
	background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
	color: #fff;
	border: 2rpx solid #fbbf24;
}

.action-btn.warning:hover {
	background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
	border-color: #f59e0b;
	box-shadow: 0 4rpx 12rpx rgba(245, 158, 11, 0.3);
}

/* ============= 快捷操作样式 ============= */
.quick-actions-section {
	padding: 24rpx;
}

.action-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s;
}

.action-card:hover {
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
	transform: translateY(-4rpx);
}

.action-card-header {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
	padding-bottom: 16rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.action-icon {
	font-size: 48rpx;
	margin-right: 16rpx;
	color: #1890ff;
}

.action-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1f2937;
}

.action-card-body {
	padding-top: 8rpx;
}

/* 当前值显示 */
.current-value {
	display: flex;
	align-items: center;
	padding: 20rpx 24rpx;
	background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
	border-radius: 12rpx;
	margin-bottom: 24rpx;
	border: 2rpx solid #e2e8f0;
}

.value-label {
	font-size: 28rpx;
	color: #64748b;
	margin-right: 16rpx;
}

.value-number {
	font-size: 36rpx;
	font-weight: 700;
	color: #1890ff;
}

.value-badge {
	font-size: 32rpx;
	font-weight: 700;
	padding: 8rpx 24rpx;
	border-radius: 8rpx;
	color: #fff;
}

.value-badge.level-A {
	background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.value-badge.level-B {
	background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
}

.value-badge.level-C {
	background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.value-badge.level-D {
	background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
}

.value-badge.level-E {
	background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
}

/* 输入组 */
.input-group {
	margin-bottom: 24rpx;
}

/* 快捷按钮组 */
.quick-buttons {
	display: flex;
	gap: 12rpx;
	margin-bottom: 24rpx;
	flex-wrap: wrap;
}

.quick-action-btn {
	flex: 1;
	min-width: 120rpx;
	padding: 16rpx 24rpx;
	background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
	border: 2rpx solid #cbd5e1;
	border-radius: 10rpx;
	font-size: 26rpx;
	color: #475569;
	font-weight: 500;
	transition: all 0.3s;
}

.quick-action-btn:hover {
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
	color: #fff;
	border-color: #1890ff;
	transform: translateY(-2rpx);
	box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
}

.quick-action-btn.danger {
	border-color: #fecaca;
	color: #dc2626;
}

.quick-action-btn.danger:hover {
	background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
	color: #fff;
	border-color: #ef4444;
	box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
}

/* 等级选择器 */
.level-selector {
	display: flex;
	gap: 12rpx;
	margin-bottom: 24rpx;
	flex-wrap: wrap;
}

.level-btn {
	flex: 1;
	min-width: 120rpx;
	padding: 20rpx 16rpx;
	background: #fff;
	border: 2rpx solid #e5e7eb;
	border-radius: 12rpx;
	font-size: 26rpx;
	color: #6b7280;
	font-weight: 500;
	transition: all 0.3s;
}

.level-btn:hover {
	border-color: #1890ff;
	color: #1890ff;
	transform: translateY(-2rpx);
}

.level-btn.active {
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
	color: #fff;
	border-color: #1890ff;
	box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
}

/* 违规类型选择 */
.violation-types {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 12rpx;
	margin-bottom: 20rpx;
}

.violation-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 16rpx 12rpx;
	background: #fff;
	border: 2rpx solid #e5e7eb;
	border-radius: 12rpx;
	font-size: 26rpx;
	color: #6b7280;
	transition: all 0.3s;
	gap: 6rpx;
}

.violation-btn .iconfont {
	font-size: 38rpx;
	color: #9ca3af;
	transition: all 0.3s;
}

.violation-btn:hover {
	border-color: #fbbf24;
	color: #f59e0b;
	transform: translateY(-2rpx);
}

.violation-btn:hover .iconfont {
	color: #f59e0b;
}

.violation-btn.active {
	background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
	border-color: #fbbf24;
	color: #92400e;
	box-shadow: 0 4rpx 12rpx rgba(251, 191, 36, 0.3);
}

.violation-btn.active .iconfont {
	color: #d97706;
}

/* 违规原因输入 */
.violation-reason {
	width: 100%;
	min-height: 140rpx;
	padding: 16rpx;
	border: 2rpx solid #e5e7eb;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #1f2937;
	line-height: 1.6;
	margin-bottom: 20rpx;
	background: #fff;
	transition: all 0.3s;
}

.violation-reason:focus {
	border-color: #fbbf24;
	box-shadow: 0 0 0 4rpx rgba(251, 191, 36, 0.1);
}

/* 提交按钮 */
.action-submit-btn {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
	padding: 18rpx;
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
	border: none;
	border-radius: 12rpx;
	color: #fff;
	font-size: 28rpx;
	font-weight: 600;
	box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.3);
	transition: all 0.3s;
}

.action-submit-btn:hover {
	background: linear-gradient(135deg, #0c7cd5 0%, #0958a5 100%);
	box-shadow: 0 6rpx 20rpx rgba(24, 144, 255, 0.4);
	transform: translateY(-2rpx);
}

.action-submit-btn:active {
	transform: translateY(0);
	box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
}

.action-submit-btn.warning {
	background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
	box-shadow: 0 4rpx 16rpx rgba(245, 158, 11, 0.3);
}

.action-submit-btn.warning:hover {
	background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
	box-shadow: 0 6rpx 20rpx rgba(245, 158, 11, 0.4);
}

.action-submit-btn.danger {
	background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
	box-shadow: 0 4rpx 16rpx rgba(239, 68, 68, 0.3);
}

.action-submit-btn.danger:hover {
	background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
	box-shadow: 0 6rpx 20rpx rgba(239, 68, 68, 0.4);
}

.action-submit-btn .iconfont {
	font-size: 28rpx;
}

/* 操作按钮行 */
.action-buttons-row {
	display: flex;
	gap: 12rpx;
	margin-top: 8rpx;
}

.action-buttons-row .action-submit-btn {
	flex: 1;
}

</style>